'use strict'

const { ApiController } = require('jax')
const helper = require('jax/app/utils/helper')

class Controller extends ApiController {
  // 模型
  get Model() {
    return this.ctx.model.UserActivity
  }

  // 匹配查询
  get searchKey() {
    return ['status']
  }

  // 模糊查询
  get likeKey() {
    return ['']
  }

  // 返回JSON字段
  get json() {
    return [
      'id',

      // 添加的
      'name',
      'mobile',
      'sex',
      'role',

      'goods',
      // 'goodsName',
      // 'goodsNum',
      // 'channel',
      // 'goodsImages',

      'activityId',

      'startTime',
      'endTime',
      'activityDate',
      'activityNo',
      'status',
      'storeName',
      'remark',
    ]
  }

  // 查询前
  async beforeIndex() {
    const { ctx } = this
    const { query } = ctx

    const filter = {
      userId: ctx.state.user.id,
    }

    return {
      filter,
    }
  }

  // 格式化
  async formatData(item) {
    const { ctx, config } = this

    const newItem = helper.exclude(item, ['createdAt', 'isDelete', 'isOpen', 'updatedAt'])

    newItem.qrcode = config.host + '/api/qrcode/?text=' + item.id

    if (this.isShow) {
      // 门店
      await ctx.model.Store.findOne({
        _id: item.storeId,
      }).then((res) => {
        if (res) {
          newItem.store = {
            id: item.storeId,
            storeName: res.storeName,
            lng: res.lng,
            lat: res.lat,
          }
        }
      })
    }

    return newItem
  }

  // 详情查询前
  async beforeShow(filter) {
    const { ctx } = this
    filter.userId = ctx.state.user.id
  }

  // 预约活动
  async create() {
    const { ctx } = this
    const { helper } = ctx
    const { user } = ctx.state
    const { body } = ctx.request
    const { ACTIVITY_STATUS_AUDIT_REFUSE, ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT } =
      this.config.constant

    const keys = ['activityId', 'name', 'mobile', 'sex', 'role', 'goods']
    const data = helper.validate(body, {
      required: keys,
      include: [...keys, 'remark'],
    })

    const activity = await ctx.model.Activity.findOne({
      _id: data.activityId,
    })

    if (!activity) throw '活动不存在'
    if (activity.status !== 0) throw '当前时间段无法预约'
    if (activity.isOpen !== true) throw '活动已关闭'

    // 判断用户今天是否已经预约过
    await ctx.model.UserActivity.findOne({
      userId: user.id,
      activityDate: activity.activityDate,
      status: {
        $nin: [ACTIVITY_STATUS_AUDIT_REFUSE, ACTIVITY_STATUS_CANCEL],
      },
    }).then((res) => {
      if (res) throw `${activity.activityDate}已预约` // 已预约
    })

    // 门店
    const store = await ctx.model.Store.findOne({
      _id: activity.storeId,
    }).then((res) => {
      if (!res) throw '门店不存在'
      return res
    })

    const userInfo = await ctx.model.User.findOne({
      _id: user.id,
    })

    const userActivity = await ctx.model.UserActivity.create({
      ...data,
      activityNo: helper.getOrderNo(),
      activityId: activity.id,
      activityDate: activity.activityDate,
      startTime: `${activity.activityDate} ${activity.startTime}:00`,
      endTime: `${activity.activityDate} ${activity.endTime}:59`,

      storeId: store.id,
      storeName: store.storeName,

      userId: user.id,
      name: userInfo.name || userInfo.nickname,
      mobile: userInfo.mobile,
    })

    activity.status = ACTIVITY_STATUS_AUDIT_WAIT // 已预约（待审核）
    activity.userId = user.id
    await activity.save()

    userInfo.activityCount += 1
    await userInfo.save()

    ctx.body = {
      code: 0,
      msg: 'success',
      data: {
        id: userActivity.id,
      },
    }
  }

  // 取消预约
  async cancel() {
    const { ctx } = this
    const { helper } = ctx
    const { user } = ctx.state
    const { body } = ctx.request
    const { ACTIVITY_STATUS_CANCEL, ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_VERIFY_WAIT } =
      this.config.constant

    const keys = ['activityId']
    const data = helper.validate(body, {
      required: keys,
      include: keys,
    })

    const userActivity = await ctx.model.UserActivity.findOne({
      _id: data.activityId,
      userId: user.id,
    })

    if (!userActivity) throw '获取预约信息失败'
    if (![ACTIVITY_STATUS_AUDIT_WAIT, ACTIVITY_STATUS_VERIFY_WAIT].includes(userActivity.status))
      throw '无法取消'

    userActivity.status = ACTIVITY_STATUS_CANCEL // 已取消
    await userActivity.save()

    // 将活动改为可以预约
    await ctx.model.Activity.findOneAndUpdate(
      {
        _id: userActivity.activityId,
      },
      {
        status: 0,
      }
    )

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }

  // 预约评论
  async comment() {
    const { ctx } = this
    const { helper } = ctx
    const { user } = ctx.state
    const { body } = ctx.request
    const { ACTIVITY_STATUS_VERIFY_SUCCESS, ACTIVITY_STATUS_SUCCESS } = this.config.constant

    const keys = ['activityId', 'score', 'content']
    const data = helper.validate(body, {
      required: keys,
      include: [...keys, 'images'],
    })

    const userActivity = await ctx.model.UserActivity.findOne({
      _id: data.activityId,
      userId: user.id,
    })

    if (!userActivity) throw '获取预约信息失败'
    if (userActivity.status !== ACTIVITY_STATUS_VERIFY_SUCCESS) throw '无法评论'

    userActivity.status = ACTIVITY_STATUS_SUCCESS // 已完成
    await userActivity.save()

    userActivity.comment = {
      score: data.score,
      content: data.content,
      images: data.images,
    }
    await userActivity.save()

    // 将活动改为可以预约
    // await ctx.model.ActivityComment.create({
    //   ...data,
    //   userId: user.id,
    // })

    ctx.body = {
      code: 0,
      msg: 'success',
    }
  }
}

module.exports = Controller
